package javax.per.toolkit.search;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import tools.Env;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Properties;
import java.util.Iterator;

import javax.per.toolkit.file.FileUtil;
import javax.per.toolkit.tools.Fun;

public class ff {
	
	
	private static String path=Env.get("tempFileDir").replaceAll("\\\\","/")+"/ff/"+"tmp.tmp";

	/**
	 * @param args
	 */
	public static void preff(String[] args) {
		if(new File(path).exists())
			new File(path).delete();
		String str=Env.get("FileSearchDir");
		String[] dirs=str.split(";");
		for(String dir:dirs)
			store(Fun.getSubFiles(dir));
	}

	private static void store(List<File> list){
		try{
		
		BufferedWriter bw=FileUtil.getAppendWriter(path);
		for(File f:list){
			bw.write(f.getName().toUpperCase()+"="+f.getAbsolutePath().replaceAll("\\\\","/")+"\n");
		}
		bw.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		for(String str:args){
			if(str.equalsIgnoreCase("-update")){
				preff(null);
				return;
			}
		}
		
		try{
		String reg=Fun.getConsoleString();
		boolean isReg=false;
		boolean valuePath=false;
		for(String s:args)
		{	
			if(s.equalsIgnoreCase("-r")){
				isReg=true;
			}
			if(s.equalsIgnoreCase("-p")){
				valuePath=true;
			}
		}

		if(!new File(path).exists()){
			preff(null);			
		}
		List<String> fileList=new ArrayList<String>();
		if(!isReg)
		reg=Fun.escapeStrForRep(reg);
		if(valuePath&&!isReg)
		reg=reg.replaceAll("\\\\","/");
		reg=reg.toUpperCase();

		Pattern pa=Pattern.compile(reg);
	
		Properties pros=new Properties();
		pros.load(new FileInputStream(path));
		Iterator<Object> it=pros.keySet().iterator();
		while(it.hasNext()){
			if(!valuePath){
				String key=(String)it.next();
				Matcher ma=pa.matcher(key);
				if(ma.find()){
					fileList.add((String)pros.get(key));
				}
			}
			else{
				String key=(String)pros.get(it.next());
				Matcher ma=pa.matcher(key.toUpperCase());
				if(ma.find()){
					fileList.add(key);
				}
			}
		}		
		//Fun.setShowLineNumber(true);
		Fun.setSeparator("\n");
		Fun.pl(fileList);
		Fun.pause();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
